package org.jmc.refmanager.web.wicket.page.admin;

import java.util.Iterator;
import java.util.List;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.domain.service.UserManager;
import org.jmc.refmanager.util.Util;
import org.jmc.refmanager.web.wicket.model.UserModel;

public class SortableUserDataProvider extends SortableDataProvider<User> {
	private static final long serialVersionUID = 1L;

	@SpringBean(name="userManager")
	private UserManager userManager;
	
	private String matricule;
	
	/**
	 * 
	 */
	public SortableUserDataProvider(String filterByMatricule) {
		super();
		InjectorHolder.getInjector().inject(this);
		setSort("matricule", true);
		this.matricule = filterByMatricule;
	}

	@Override
	public Iterator<? extends User> iterator(int first, int count) {
		List<User> users = null;
		SortParam sp = getSort();
		QueryParam queryParam = new QueryParam(first, count, sp.getProperty(), sp.isAscending());
		if (Util.isEmptyOrBlank(matricule)) {
			users = userManager.list(queryParam);
		} else {
			users = userManager.listByMatricule(queryParam, matricule);
		}
		return users.iterator();
	}

	@Override
	public IModel<User> model(User user) {
		return new UserModel(user);
	}

	@Override
	public int size() {
		if (Util.isEmptyOrBlank(matricule)) {
			return userManager.count();
		} else {
			return userManager.countByMatricule(matricule);
		}
	}

}
